package org.bigk.invoices.services;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;
import org.bigk.invoices.services.taxesconfig.TaxConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service("taxesConfigService")
@Transactional
public class TaxesConfigService {

	private List<TaxConfig> taxesConfigs;
	
	public TaxesConfigService() {
		
		this.taxesConfigs = new ArrayList<TaxConfig>();
		
		List<Double> listBefore2011 = new ArrayList<Double>();
		listBefore2011.add(new Double(0.22));
		listBefore2011.add(new Double(0.07));
		listBefore2011.add(new Double(0.03));
		taxesConfigs.add(
				new TaxConfig(parseDate("01-01-1990"), listBefore2011));
		
		List<Double> listAfter2011 = new ArrayList<Double>();
		listAfter2011.add(new Double(0.23));
		listAfter2011.add(new Double(0.08));
		listAfter2011.add(new Double(0.05));
		taxesConfigs.add(
				new TaxConfig(parseDate("01-01-2011"), listAfter2011));
		
	}

	private Date parseDate(String dateStr) {
		try {
			return DateUtils.parseDate(dateStr, new String[] {"dd-MM-yyyy"});
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public List<TaxConfig> getTaxesConfigs() {
		return taxesConfigs;
	}

	public void setTaxesConfigs(List<TaxConfig> taxesConfigs) {
		this.taxesConfigs = taxesConfigs;
	}

	/**
	 * Gets tax configuration for given date. I believe, for dates before
	 * 2011-01-01 those will be taxes 0.03, 0.07, 0.22 and for dates equal or
	 * after 2011-01-01 those will be 0.04, 0.08, 0.23.
	 * 
	 * @param date
	 *            date for which taxes will be returned
	 * @return taxes configuration
	 */
	public TaxConfig getTaxConfigByDate(Date date) {
		TaxConfig tc = null;

		if (taxesConfigs != null) {
			for (TaxConfig tci : this.taxesConfigs) {
				if (tci.getStartDate().compareTo(date) <= 0) {
					tc = tci;
				} else {
					break;
				}
			}
		}
		
		return tc;
	}
}
